package com.example.shushiyunsst.fragment.main.mine.child

import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.album.Album
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.upload_file.UploadFileWorker
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.AddPayingWayFragmentBinding
import com.example.shushiyunsst.util.ADD_PAYING_WAY
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback

/**
 * 添加支付方式
 * */
@Route(path = ADD_PAYING_WAY)
class AddPayingWayFragment : BaseDataBindingFragment<AddPayingWayFragmentBinding>(),
    View.OnClickListener, OnTextListener {

    companion object {
        fun newInstance(): AddPayingWayFragment {
            val args = Bundle()

            val fragment = AddPayingWayFragment()
            fragment.arguments = args
            return fragment
        }

        const val WEI_CHAT_PAY = 1

        const val A_LI_PAY = 2

        const val BANK_CARD_PAY = 3
    }


    private var payWay1 = WEI_CHAT_PAY


    override fun layoutId(): Int {
        return R.layout.add_paying_way_fragment
    }

    private var mWeiChatPayRealName = ""

    private var mWeiChatPayAccount = ""

    private var mAliPayRealName = ""

    private var mAliPayAccount = ""

    private var mBankCardRealName = ""

    private var mBankCardAccount = ""

    private var mBankCardOpenAccount = ""

    private var mBankCardBankBranch = ""

    private var selectPicStr = ""

    private var mUploadFileWorker: UploadFileWorker? = null


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "添加收款方式"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this



        changLayout()
    }

    private fun changLayout() {

        var icon = 0
        var payWayTitle = ""
        when (payWay1) {
            WEI_CHAT_PAY -> {
                viewBinder.mWeiChatPayLayout.visibility = View.VISIBLE
                viewBinder.mAliPayLayout.visibility = View.GONE
                viewBinder.mBankCardLayout.visibility = View.GONE
                icon = R.drawable.ic_we_chat_pay
                payWayTitle = "微信"
            }
            A_LI_PAY -> {
                viewBinder.mWeiChatPayLayout.visibility = View.GONE
                viewBinder.mAliPayLayout.visibility = View.VISIBLE
                viewBinder.mBankCardLayout.visibility = View.GONE
                icon = R.drawable.ic_a_li_pay
                payWayTitle = "支付宝"
            }
            BANK_CARD_PAY -> {
                viewBinder.mWeiChatPayLayout.visibility = View.GONE
                viewBinder.mAliPayLayout.visibility = View.GONE
                viewBinder.mBankCardLayout.visibility = View.VISIBLE
                icon = R.drawable.ic_bank_card_pay
                payWayTitle = "银行卡"
            }
        }

        viewBinder.btnChange.text = payWayTitle
        if (icon != 0) {
            val leftDrawable = ContextCompat.getDrawable(_mActivity, icon)
            leftDrawable?.setBounds(0, 0, leftDrawable.intrinsicWidth, leftDrawable.intrinsicHeight)

            val rightDrawable =
                ContextCompat.getDrawable(_mActivity, R.drawable.ic_round_album_arrow_right_24)
            rightDrawable?.setBounds(
                0,
                0,
                rightDrawable.intrinsicWidth,
                rightDrawable.intrinsicHeight
            )
            viewBinder.btnChange.setCompoundDrawables(leftDrawable, null, rightDrawable, null)
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.createAccount -> {
                viewBinder.mProgressBar.visibility = View.VISIBLE
                mCreateAccount()
            }
            R.id.mWeiChatPaySelectPic, R.id.mAliPaySelectPic -> {
                selectPic()
            }
            R.id.btnChange -> {

                showPop()
            }
        }
    }

    private fun mCreateAccount() {
        if (mUploadFileWorker != null) {
            Toast.makeText(_mActivity, "正在发送", Toast.LENGTH_SHORT).show()
            return
        }
        if (selectPicStr.isNotEmpty()) {

            val mutableListOf = mutableListOf<String>()

            mutableListOf.add(selectPicStr)
            mUploadFileWorker = UploadFileWorker()
            mUploadFileWorker?.setListener(object :
                UploadFileWorker.UpLoadOverListener {
                override fun onUpLoadOver(res: List<String>) {
                    mUploadFileWorker = null
                    viewBinder.mProgressBar.visibility = View.GONE
                    onSending(res)
                }
            })?.doWork(mutableListOf)
        } else {
            onSending(emptyList())
        }

    }

    private fun onSending(res: List<String>) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val payAccount = when (payWay1) {
            WEI_CHAT_PAY -> mWeiChatPayAccount

            A_LI_PAY -> mAliPayAccount

            BANK_CARD_PAY -> mBankCardAccount

            else -> ""
        }

        val realName = when (payWay1) {
            WEI_CHAT_PAY -> mWeiChatPayRealName

            A_LI_PAY -> mAliPayRealName

            BANK_CARD_PAY -> mBankCardRealName

            else -> ""
        }

        var imgUrl = if (res.isEmpty()) "" else res[0]

        imgUrl = if (payWay1 == BANK_CARD_PAY) payAccount else imgUrl

        val maps = mapOf(
            "bankName" to mBankCardOpenAccount,
            "childBankName" to mBankCardBankBranch,
            "imgUrl" to imgUrl,
            "payAccount" to payAccount,
            "payType" to payWay1,
            "realName" to realName,
            "uid" to userInfo?.uid,
        )
        RestClient.builder()
            .url(R.string.updatePayment)
            .raw(JSON.toJSONString(maps))
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
                onBackPressedSupport()

            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
            }.error { code, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
            }
            .build()
            .post()
    }

    private fun selectPic() {
        Album.getInstance()
            .singleImage()
            .onSuccess {
                if (it.isNotEmpty()) {
                    selectPicStr = it[0].path

                    val img = when (payWay1) {
                        WEI_CHAT_PAY -> viewBinder.mWeiChatPaySelectPic
                        A_LI_PAY -> viewBinder.mAliPaySelectPic
                        BANK_CARD_PAY -> viewBinder.mWeiChatPaySelectPic
                        else -> viewBinder.mWeiChatPaySelectPic
                    }
                    img.clearColorFilter()

                    GlideApp.with(this)
                        .load(selectPicStr)
                        .into(img)
                }
            }
            .onFailed { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .execute(childFragmentManager)
    }

    private fun showPop() {
        val addPayingWayPop = AddPayingWayPop(_mActivity)
        addPayingWayPop.setPayWay(payWay1)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    val payWay = addPayingWayPop.getPayWay()
                    if (payWay1 != payWay) {
                        payWay1 = payWay
                        changLayout()
                    }
                }
            })
            .asCustom(addPayingWayPop)
            .show()
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.mWeiChatPayRealName -> {
                mWeiChatPayRealName = s.toString()
            }
            R.id.mWeiChatPayAccount -> {
                mWeiChatPayAccount = s.toString()
            }
            R.id.mAliPayRealName -> {
                mAliPayRealName = s.toString()
            }
            R.id.mAliPayAccount -> {
                mAliPayAccount = s.toString()
            }
            R.id.mBankCardRealName -> {
                mBankCardRealName = s.toString()
            }
            R.id.mBankCardAccount -> {
                mBankCardAccount = s.toString()
            }
            R.id.mBankCardOpenAccount -> {
                mBankCardOpenAccount = s.toString()
            }
            R.id.mBankCardBankBranch -> {
                mBankCardBankBranch = s.toString()
            }
        }
    }


}